<template>
  <div class="app-container page-wood-sales-note">
       
    <el-row :gutter="10" class="sumbit-btn-group mb8">
      <template v-if="!salesId">
       <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="saveHandleAdd"
          v-hasPermi="['business:salesOrder:add']"
          >保存并新增</el-button
        >
      </el-col>
      <template v-if="form.orderStatus != 3">
        <el-col :span="1.5">
            <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="submitForm"
            v-hasPermi="['business:salesOrder:add']"
            >保存</el-button
            >
        </el-col>
      </template>
      </template>
      <template v-else>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="newAddSell"
            v-hasPermi="['business:salesOrder:add']"
            >新增</el-button
          >
        </el-col>
        <template v-if="form.orderStatus != 3">
          <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            @click="setAuditStatus"
            v-hasPermi="['business:salesOrder:edit']"
            >{{ form.auditStatus == 0 ? "审核" : "反审核" }}</el-button
          >
        </el-col>
        </template>
        <template v-if="form.auditStatus != 1">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="submitForm"
              v-hasPermi="['business:salesOrder:add']"
              >保存</el-button
            >
          </el-col>
        </template>
      </template>
      <template v-if="form.auditStatus == 1">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-switch-button"
            size="mini"
            @click="handleCloseOpen"
            v-hasPermi="['business:salesOrder:edit']"
            >{{ form.orderStatus == 3 ? "开启" : "关闭" }}</el-button
          >
        </el-col>
      </template>
      <template v-if="form.auditStatus == 1 && form.orderStatus != 3">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="SalesOutbound"
            >销售出库</el-button
          >
        </el-col>
      </template>
    </el-row>

    <div class="table-area">
      <el-form
        :model="form"
        ref="form"
        :inline="true"
        v-show="showSearch"
        :rules="rules"
        label-width="90px"
      >
  
        <el-form-item label="客户" prop="customerName">
          <SupplierSelect
                :typeSelect = customer
                v-model="form.customerName"
                placeholder="请输入客户"
                :disabled="disabled"
            />
        </el-form-item>
     
          <el-form-item label="单据日期"  prop="billTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.billTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择单据日期"
            :disabled="disabled"
          >
          </el-date-picker>
        </el-form-item>
 
          <el-form-item label="单据编号" prop="salesId">
            <el-input
            v-model="form.salesId"
            placeholder="请输入单据编号"
            :disabled="true"
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="销售员" prop="salesName">
           <SupplierSelect
                  :typeSelect = sales
                  v-model="form.salesName"
                  placeholder="请输入销售员"
                  :disabled="disabled"
              />
        </el-form-item>
    
        <el-form-item label="税率(%)" prop="taxRate">
          <el-input-number v-model="form.taxRate" controls-position="right"  :min="0" :max="100"></el-input-number>
        </el-form-item>
  
        <JustTimeInventory
          @selectItemsClick="selectItemsClick"/>
      <!-- 表格开始 -->
      <TableForm
          ref="TableForm"
          :list="form.woodSalesOrderGoodsList"
          :column="getSalesTableData"
          :summary="true"
          :loading="loading"
          :disabled="disabled"
      >
      </TableForm>
      <!-- 表格结束 -->
      
      <!-- 备注信息 -->
      <el-form-item class="form-remark" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入备注信息"
            v-model="form.remark"
            clearable
            size="small"
            rows="5"
          />
        </el-form-item>
        <img
          v-if="form.auditStatus == 1 && form.orderStatus != 3"
          :src="img.audit"
          class="img-audit"
        />
         <img v-if="form.orderStatus == 3" :src="img.close" class="img-audit" />
      </el-form>
    </div>
  </div>
</template>

<script>

import JustTimeInventory from "@/components/JustTimeInventory";
import TableForm from "@/components/TableForm/preset";
import SupplierSelect from "@/components/SupplierSelect";

export default {
  name: "salesDelivery",
  components: {
    JustTimeInventory,
    TableForm,
    SupplierSelect,
    },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示
      showSearch: true,
      // 商品实时库存查询参数
      queryParams: {
        pageSize:10,
        pageNum:1,
        baleNum: null,
      },
      // 表单参数
      form: {
        salesId:"",
        isStatus: "0",
        auditStatus: 0,
        taxRate:0,
        // 销售订单信息表格数据
        woodSalesOrderGoodsList: [
          {
            baleNum: "", // 包号
            goodsName: "", // 品名
            brandName: "", // 品牌
            level:"", //等级
            warehouse: "", // 仓库
            ply: 0, // 厚度
            width: 0, // 宽度
            length: 0, // 长度
            sliceCount: 0, // 片数
            pieceCount: 0, // 件数
            inCount: 0, // 方数
            oneCount: 0, // 单包方数
            includedTaxPrice: 0, //含税单价
            outCount: 0, //出库方数
            price: 0, // 单价
            money: 0, // 金额
            goodsStatus: "", // 货物状态
            pactName: "", //开证公司
            remark: "", // 备注
            taxRate:0,
            gcountId: ""
          },
        ],
      },
      // 表格数据
      getSalesTableData :[
          { label: "包号", changeBlur: this.searchBaleNum},
          { label: "品名"},
          { label: "品牌"},
          { label: "等级"},
          { label: "仓库"},
          {
            label: "厚度(mm)",
            inputType: "none",
            summary: true
          },
          {
            label: "宽度(mm)",
            inputType: "none",
            summary: true
          },
          {
            label: "长度(m)",
            inputType: "none",
            summary: true
          },
          {label: "片数"},
          {label: "件数",afterChange:this.moneyCount},
          {label: "单包方数", afterChange:this.moneyCount},
          {label: "方数", inputType: "none"},
          {
            label: "含税单价", 
            value: 'includedTaxPrice',
            onchange: this.moneyCount,
            },
          {label: "金额"},
          {label: "货物状态"},
          {label: "开证公司", inputType: "none",value:'pactName'},
          {label: "备注(批量)"},
      ],
      // 表单校验
      rules: {
          customerName: [
            { required: true, message: '客户不能为空', trigger: "blur"},
          ],
          billTime: [
            { required: true, message: '单据日期不能为空', trigger: "blur"},
          ],
          orderId: [
            { required: true, message: '订单号不能为空', trigger: "blur"},
          ],
          salesName: [
            { required: true, message: '销售员不能为空', trigger: "blur"},
          ],
    
      },
      // 业务员
      salesman:null,

      //订单号 
      salesId: "",
      mouseShow:false,
      price:null,
      // 组件替换条件
      customer:'customerName',
      sales: 'nickName',
    
      img: {
        audit: require("@/assets/images/bg@audit.png"),
        close: require("@/assets/images/bg@closed.png"),
      },
    };
  },
  created() {
    let { id } = this.$route.params;
    this.salesId = id;
    id && this.getSalesDetail()
    
    if( this.form.salesId == "" && this.salesId == null) {
       this.$Api.onlyId.getId().then(( res) =>{
        let { data} = res;
        this.form.salesId = data
    })
    }
  },
  computed: {
      disabled() {
        if( this.form.auditStatus == 1) {
           return  !!this.orderId
        }
      },
    
  },
  methods: {
    // 包 数据选择
    selectItemsClick(newData){
      newData.forEach((v)=>{
        v.oneCount = Number(v.inCount) / Number(v.pieceCount)
      })
      this.form.woodSalesOrderGoodsList = newData
  
    },
    // 金额计算 ： 单价 * 方数  
    moneyCount(d) {
      let {inCount, includedTaxPrice } = d
      let t = ((includedTaxPrice || 0) * (inCount || 0)).toFixed(3)
      this.price = includedTaxPrice
      d.money = t
      },
    // 查询包号数据
    searchBaleNum(d,index){
      let { woodSalesOrderGoodsList } = this.form
      let {  pieceCount ,baleNum} = d;

      if(baleNum == null || baleNum == "") {
         this.$message.error('包号为空');
         this.reset()
      } else {
        this.queryParams.baleNum = baleNum;
        this.$Api.storage.report.inventory( this.queryParams).then( (res) =>{
          
            if(res.rows.length == 0) {
              this.$message.error('不存在此包号，请重新输入')
            } else{
             
              res.rows.forEach( (v) =>{
                  woodSalesOrderGoodsList = woodSalesOrderGoodsList.splice(index,1,v)
                })
            }
          
      
        }).catch( ()=>{})
      }
    },

    // 获取详情
    getSalesDetail() {
      let { salesId } = this;
        this.$Api.sales.order.detail(salesId).then((res) => {
        let { data, code } = res;
        if (code === 200) {
          data.woodSalesOrderGoodsList = data.woodSalesOrderGoodsList
          
          this.form = data;
          data.woodSalesOrderGoodsList.forEach( (v) =>{
            this.form.taxRate = v.taxRate;
            v.oneCount = Number(v.count) / Number(v.pieceCount);
            v.inCount = v.count
          })
        }
      });
    },
    // 表格重置
    reset() {
       this.form.woodSalesOrderGoodsList=[
        {
           baleNum: null, // 包号
            goodsName: null, // 品名
            brandName: null, // 品牌
            level:null, //等级
            warehouse: null, // 仓库
            ply:null, // 厚度
            width:null, // 宽度
            length:null, // 长度
            sliceCount:null, // 片数
            pieceCount:null, // 件数
            inCount:null, // 方数
            includedTaxPrice: null, // 单价
            money: null, // 金额
            goodsStatus: null, // 货物状态
            pactName: null, //开证公司
            remark: null, // 备注
        },
      ]
    },
  
    /** 保存提交按钮 */
    submitForm() {
      let {taxRate, woodSalesOrderGoodsList} = this.form
      let { price} = this
     
      woodSalesOrderGoodsList.forEach( (item) =>{
          item.taxRate = taxRate
          item.includedTaxPrice = price
          item.gcountId
          item.count = item.inCount
          item.outCount = 0
        })
 
        this.$refs["form"].validate( (pass,error) =>{
        pass &&
        this.$refs["TableForm"].checkForm(
          ( TableFormPass, error) =>{
            if (TableFormPass) {
              if( price != undefined || price != null) {
              this.$Api.sales.order.add(this.form).then((res) => {
              if( res.code == 200) {
                this.salesId = res.data
                this.msgSuccess("操作成功");
                const id = this.salesId;
                    let path = `/sales/salesOrder/list/${id}`;
                    this.$router.push({
                      path,
                    });  
              }else {
                this.$message.error('操作失败');
              }
            });
            }else{
              this.$message.error('请输入含税单价');
            } 
            }
          }
        )
      })
    },
        //保存并新增 
    saveHandleAdd() {
      this.submitForm()
      this.reset()
      this.form.salesId = null
    },
    // 新增
    newAddSell () {
      this.$router.push({ path: '/sale/receipts/order' })
      this.reset();
    },
    // 审核与反审核 审核状态;0未审核 1已审核
    setAuditStatus(state){
      let { salesId } = this;
      let { auditStatus} = this.form;
      let setStatus = auditStatus == 0 ? '审核' : '反审核'
      this.$confirm('是否确认'+`${ state == 2 ? "保存" : setStatus }`+'销售订单信息编号为"' + salesId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            let nextAudit = auditStatus == 1 ? 0 : 1;
            this.$Api.sales.order.setState({
              ids: [ salesId ],
              auditStatus:nextAudit,
              isStatus: 0,
              }).then((res) => {
              if( res.code == 200) {
                this.getSalesDetail()
                this.msgSuccess( `${auditStatus == "1" ? '反审核' : '审核'}`+"成功");
              }else {
                this.$message.error('操作失败');
    
              }
            }).catch(() => {});
        }).catch(() => {});
        
    },
    // 开启关闭操作
    handleCloseOpen() {
      let { salesId } = this;
      let ids = [];
      ids.push(salesId)
      let { orderStatus } = this.form;
      this.$confirm('是否确认'+ `${orderStatus == "0" ? '关闭' : '开启'}` +'采购订单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            this.$Api.sales.order.setState({
            ids: ids,
            orderStatus,
            isStatus: 1
            }).then(() => {
                this.getSalesDetail();
                this.msgSuccess(`${orderStatus == "0" ? '关闭' : '开启'}`+"成功");
            }).catch(() => {
            this.getSalesDetail();

          })
        });
    },
    // 销售出库
    SalesOutbound() {
        const salesId = this.form.salesId
        let path = `/sale/receipts/outbound?salesId=${salesId}`
        this.$router.push({
            path
        })
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep.page-wood-sales-note {
  .img-audit{
      position: absolute;
      right: 30px;
      bottom: 30px;
      transform: rotate(-18deg);
      pointer-events: none;
  }
  .add-wood-just-time{
    margin:0 0 15px 15px;
    .el-button--primary.is-plain{
    padding: 0;
  }
  }
  
  .sumbit-btn-group {
    margin: 0 0 20px 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }

  .disabled {
    color: #a8a8a8;
  }

  .error {
    color: #fa3e3e;
  }

  .form-remark {
      display: grid;
      margin: 20px 15px 15px;
       .el-form-item__contentt {
        display: inline-block ;
        width: 100% ;
    }
  }
 
}
</style>
